package csharp.cauth.commands;

import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.PlayerInventory;

import csharp.cauth.CAuth;
import csharp.cauth.Language;
import csharp.cauth.PlayersSL;
import csharp.cauth.PluginConfig;
import csharp.cauth.properties.InventoryProp;
import csharp.cauth.properties.PlayerProp;
import csharp.cauth.utils.MD5;

/**
 * @author Ярослав (CSharp) "/setpass" command. Used for change player password.
 */
public class CASetPassword implements CommandExecutor
{
	private static CAuth plugin;

	public CASetPassword(CAuth cAuth)
	{
		CASetPassword.plugin = cAuth;
	}

	@Override
	public boolean onCommand(CommandSender sender, Command command,
			String label, String[] split)
	{
		if (sender instanceof Player)
		{
			Player player = (Player) sender;

			if (split.length > 2)
			{
				PlayerProp temp = null;

				for (PlayerProp playerProp : CAuth.players)
				{
					if (playerProp.getLogin()
							.equalsIgnoreCase(player.getName())
							&& playerProp.getPassword().equalsIgnoreCase(
									MD5.getHash(split[0])))
					{
						temp = playerProp;

						break;
					}
				}

				if (temp != null)
				{
					if (split[1].equalsIgnoreCase(split[2]))
					{
						CAuth.players.remove(temp);

						temp.setPassword(MD5.getHash(split[1]));
						temp.setLastLoc(player.getLocation());

						player.teleport(player.getWorld().getSpawnLocation());

						CAuth.players.add(temp);
						CAuth.authorized.remove(plugin.getServer().getPlayer(
								temp.getLogin()));

						PlayerInventory inventory = player.getInventory();

						CAuth.unauthorized.put(player, new InventoryProp(
								inventory));

						inventory.clear();
						inventory.setBoots(null);
						inventory.setChestplate(null);
						inventory.setHelmet(null);
						inventory.setLeggings(null);

						player.getInventory().clear();

						if (PluginConfig.useMySQL)
							PlayersSL.updatePassword(temp.getId(),
									temp.getPassword());
						else
							PlayersSL.savePlayers();

						player.sendMessage("[CAuth] "
								+ Language.PASSWORD_SUCCESSFULLY_CHANGED);
					}
					else
					{
						player.sendMessage("[CAuth] "
								+ Language.PASSWORDS_NOT_EQUALS);
					}
				}
				else
				{
					player.sendMessage("[CAuth] "
							+ Language.PASSWORDS_NOT_EQUALS);
				}

				return true;
			}
		}

		return false;
	}
}
